<template>
  <div class="MyRing">
    <byd-header />
    <div class="container">
      <p style="font-size: 18px; margin: 10px 0">热门车辆...</p>
      <el-row :gutter="20">
        <el-col :span="18">
          <div class="grid-content bg-purple">
            <div class="contain" style="
                background-color: white;
                margin-left: 35px;
                border-radius: 10px;
              ">
              <!-- 热门车辆推荐 -->
              <ul class="cartoon" v-if="vehicle">
                <!-- 动画容器 -->
                <li v-for="item in vehicle" :key="item.cid">
                  <!-- 第一组 -->
                  <img :src="item.lpic" alt="" />
                  <h4 style="color: gray; text-align: center">
                    指导价:{{ item.gprice }}万元
                  </h4>
                  <p>{{ item.title }}</p>
                  <el-button type="info" size="mini" plain @click="luyou">查看详情</el-button>
                </li>
                <li v-for="item in vehicle" :key="item.lpic">
                  <!-- 第二组 -->
                  <img :src="item.lpic" alt="" />
                  <h4 style="color: gray; text-align: center">
                    指导价:{{ item.gprice }}万元
                  </h4>
                  <p>{{ item.title }}</p>
                  <el-button type="info" size="mini" plain @click="luyou">查看详情</el-button>
                </li>
              </ul>
            </div>
          </div>
          <!-- 大家都在聊  -->
          <div class="message">
            <p style="font-size: 18px; margin: 18px 0 3px">大家都在聊...</p>
            <el-button class="el-icon-edit" type="text" @click="open3()" style="
                font-size: 18px;
                margin-top: 8px;
                border: 0;
                background-color: #ebe7e7;
              " :plain="true">发 布</el-button>
          </div>
          <!-- 车友圈发布 -->
          <el-dialog :visible.sync="dialog" width="50%">
            <el-form ref="form" :model="form" label-width="100px">
              <el-form-item label="发布内容">
                <!-- 内容发布文本框 -->
                <el-input type="textarea" rows="4" placeholder="请输入内容" v-model="form.msg"></el-input>
              </el-form-item>
              <el-form-item label="上传图片">
                <el-upload class="upload-demo" action="http://8.136.106.157:8888/upload" list-type="picture-card"
                  :limit="3" :on-success="handleSuccess" multiple name="uploadFile">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail" style="border-color: transparent" :src="file.url"
                      alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialog = false">取消</el-button>
              <el-button id="judge" type="primary" @click="

  open2();
dialog = false;
onSubmit();
              " :plain="true">发布</el-button>
            </span>
          </el-dialog>
          <router-view />
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple-light" v-if="comment">
            <template>
              <div class="block">
                <el-carousel height="190px">
                  <el-carousel-item v-for="i in 4" :key="i">
                    <img :src="
                      require(`../../public/pic/advert/advertising${i}.webp`)
                    " alt="" />
                  </el-carousel-item>
                </el-carousel>
              </div>
            </template>
            <div style="display: flex; justify-content: space-between">
              <span style="margin: 10px 0">大家都在看</span>
              <el-button style="border: 0; background: #ebe7e7" @click="change">
                <i class="el-icon-refresh">换一换</i>
              </el-button>
            </div>
            <div v-for="(item, i) of comment" :key="i">
              <p>{{ i + 1 }}、{{ item.msg }}</p>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-button :round="true" id="door" class="active" :plain="true" @click="open1">
        聊天室
      </el-button>

      <div id="home">
        <div class="right">
          <div class="chat-header">
            车友交流区
            <i class="el-icon-close" @click="close"></i>
          </div>
          <div class="body im-record" id="im-record">
            <div class="ul">
              <!-- user为靠右展示样式，如果uid一致说明是本人 -->
              <div class="li" v-for="(item, index) in messageList" :class="{ user: item.uid === uid }" :key="index">
                <template v-if="item.type === 1">
                  <p class="join-tips">{{ item.msg }}</p>
                </template>
                <template v-else>
                  <template v-if="item.phone == 18896556035">
                    <p class="message-date">
                      <span class="m-phone" style="color: #cd5c5c">🚗客服小海</span>
                      {{ item.date }}
                    </p>
                    <p style="line-height: 30px; font-size: 20px; color: #00b1a9">
                      {{ item.msg }}
                    </p>
                  </template>

                  <template v-else-if="item.phone == 13279659259">
                    <p class="message-date">
                      <span class="m-phone" style="color: #cd5c5c">🚗客服小豹</span>
                      {{ item.date }}
                    </p>
                    <p style="line-height: 30px; font-size: 20px; color: #00b1a9">
                      {{ item.msg }}
                    </p>
                  </template>

                  <template v-else>
                    <p class="message-date">
                      <span class="m-phone">海豹{{
                          item.phone.replace(/(\d{7})(\d{4})/, "$2")
                      }}</span>
                      {{ item.date }}
                    </p>
                    <p class="message-box">{{ item.msg }}</p>
                  </template>
                </template>
              </div>
            </div>
          </div>
          <div class="im-footer">
            <!-- <el-input placeholder="请输入内容" v-model="input2">
    <template slot="append">.com</template>
  </el-input> -->
            <template v-if="phone == 18896556035 || phone == 13279659259">
              <el-input placeholder="请输入内容,字数限制30字 win + . 发送表情" v-model="message" class="im-footer_inp" maxlength="30"
                show-word-limit>
                <template slot="append">
                  <el-button class="im-footer_btn" type="primary" @click="adminsend">发送{{ time }}</el-button>
                </template>
              </el-input>

            </template>
            <template v-else>
              <el-input placeholder="请输入内容,字数限制30字 win + . 发送表情" v-model="message" class="im-footer_inp" maxlength="30"
                show-word-limit>
                <template slot="append">
                  <el-button :disabled="disabled" class="im-footer_btn" type="primary" @click="send">发送{{ time }}
                  </el-button>
                </template>
              </el-input>

            </template>

          </div>
        </div>
      </div>
    </div>
    <byd-footer />
  </div>
</template>

<script>
import qs from "qs";
import BydHeader from "../components/BydHeader.vue";
import BydFooter from "../components/BydFooter.vue";
import moment from "moment";
export default {
  components: { BydHeader, BydFooter },
  data() {
    return {
      disabled: false,
      time: '',
      ws: "",
      uid: this.uid,
      messageList: [],
      message: "", // 输入的消息内容

      msg: "",
      phone: "",
      // loading: false,
      dialog: false,
      plain: false,
      // page: 2,
      // data: [],
      comment: null,
      vehicle: null,
      form: {
        msg: "", //发布内容
        msg_pic1: "",
        msg_pic2: "",
        msg_pic3: "",
        // 获取当前的时间戳
        msg_time: Date.now(),
        phone: "",
        scount: 0,
      },
      urls: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  updated() {
    let scroll = document.getElementById("im-record");
    scroll.scrollTop = scroll.scrollHeight;
  },
  inject: ["reload"],
  methods: {
    open3() {
      if (!sessionStorage.getItem("phone")) {
        this.$message({
          message: "请先登录",
          type: "warning",
          center: true,
        });
      } else {
        this.dialog = true;
      }
    },
    // 聊天传递
    init() {
      if (window.WebSocket) {
        let user = {};
        if (sessionStorage.getItem("WEB_IM_USER"))
          user = JSON.parse(sessionStorage.getItem("WEB_IM_USER"));
        this.phone = sessionStorage.getItem("phone") || "";
        this.uid = user.uid || "";

        // 监听回车事件
        if (this.phone == 18896556035 || this.phone == 13279659259) {
          let vm = this;
          document.onkeydown = function (event) {
            let e = event || window.event;
            if (e && e.keyCode == 13) {
              // console.log("触发enter");
              vm.adminsend();
            }

          }
        } else {
          let vm = this;
          document.onkeydown = function (event) {
            let e = event || window.event;
            if (e && e.keyCode == 13) {
              // console.log("触发enter");
              vm.send();
            }
          }
        };
        // } else {
        //   console.log("当前浏览器不支持WebSocket！");
        // }
      }
    },
    adminsend() {
      if (!this.message) return;
      this.sendMessage(2, this.message);
    },
    // enter触发 或者 点击“发送”触发
    send() {
      if (!this.message) return;
      if (!this.time) {
        this.sendMessage(2, this.message);
        let that = this
        that.time = 5; //设定间隔时间（秒）
        that.disabled = true;
        //启动计时器，倒计时time秒后自动关闭计时器。
        let index = setInterval(function () {
          that.time--;
          if (!that.time) {
            clearInterval(index);
            that.time = ''
            that.disabled = false
          }
        }, 1000);
        //此处可写要执行的代码
        console.log('按钮事件被触发');
      } else {
        console.log('目前按钮事件不允许被触发');
      }



    },

    // 发送信息给客户端
    sendMessage(type, msg) {
      const data = {
        uid: this.uid,
        type,
        phone: this.phone,
        msg,
      };
      this.ws.send(JSON.stringify(data));
      this.message = "";
    },

    // 连接websocket
    contactSocket() {
      const that = this;
      const ws = this.ws;
      ws.onopen = function () {
        console.log("连接服务器成功");

        //没有当前人信息的话，需要缓存下
        if (!that.uid) {
          that.uid = "web_im_" + moment().valueOf();
          sessionStorage.setItem(
            "WEB_IM_USER",
            JSON.stringify({
              uid: that.uid,
              phone: that.phone,
            })
          );
        }
        that.sendMessage(1);
      };
      ws.onmessage = function (e) {
        that.messageList.push(JSON.parse(e.data));
      };
      ws.onclose = function () {
        console.log("连接已关闭");
      };
    },
    // 开启聊天室
    open1() {
      if (!sessionStorage.getItem("phone")) {
        this.$message({
          message: "请先登录",
          type: "warning",
          center: true,
          // offset: 400,
        });
        return;
      }
      document.getElementById("door").classList.remove("active");
      document.getElementById("home").classList.add("active");
    },
    // 关闭聊天室
    close() {
      document.getElementById("home").classList.remove("active");
      document.getElementById("door").classList.add("active");
    },

    save() {
      this.form.phone = sessionStorage.getItem("phone");
    },
    luyou() {
      this.$router.replace("/details");
    },
    onSubmit() {
      // 遍历urls,分别存入form表单
      this.form.msg_pic1 = this.urls[0];
      this.form.msg_pic2 = this.urls[1];
      this.form.msg_pic3 = this.urls[2];
      // 调用接口发布帖子
      this.axios
        .post("/club", qs.stringify(this.form))
        .then((res) => {
          // console.log(res);
        })
        .catch((err) => {
          return err;
        });
      // 当帖子发布成功后,刷新页面
      this.reload();
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, filelist) {
      // 获取访问网络图片的链接地址
      let url = response.urls[0];
      this.urls.push(url); //将路径保存在data.urls数组中
    },

    // 点击换一换
    change() {
      this.axios.get("/getclubs").then((res) => {
        this.comment = res.data.data;
      });
    },
    // 发布成功弹出成功消息
    open2() {
      this.$message({
        message: "发布成功",
        type: "success",
        center: true,
      });
    },
  },

  mounted() {
    this.phone = sessionStorage.getItem("phone");
    this.ws = new WebSocket("ws://8.136.106.157:8000");

    this.init();
    this.contactSocket();
    this.save();
    this.axios.get("/getclubs").then((res) => {
      this.comment = res.data.data;
    });
    this.axios.get("/get_cars?page=1").then((res) => {
      this.vehicle = res.data.data;
    });
  },
};
</script>

<style lang="scss" scoped>
// * {
//   text-align: left;
// }
// 版心
.container {
  width: 1400px;
  margin: 0 auto;
  text-align: left;
}

@media (max-width: 1400px) {
  .container {
    width: 1200px;
    margin: 0 auto;
  }
}

@media (max-width: 1200px) {
  .container {
    width: 1024px;
    margin: 0 auto;
  }
}

.MyRing {
  background-color: #ebe7e7;
}

//热门车辆动画
.contain {
  overflow: hidden;
  margin-left: 0 !important;

  .cartoon {
    width: 400%;
    animation: move 60s infinite linear;
    list-style: none;
    display: flex;

    li {
      width: 12.5%;
      text-align: center;

      img {
        width: 80%;
        display: block;
        margin: 0 auto;
      }

      .el-button {
        display: block;
        margin: 0 auto;
        margin-bottom: 10px;
      }

      .el-button:hover {
        background-color: rgb(199, 198, 198);
        border-color: rgb(199, 198, 198);
        color: white;
      }

      p {
        text-align: center;
        margin: 5px 0;
      }

      h4 {
        margin: 5px 0;
      }
    }
  }

  //鼠标悬浮,动画暂停
  .cartoon:hover {
    animation-play-state: paused;
  }
}

@keyframes move {
  100% {
    transform: translateX(-50%);
  }
}

// 帖子发布
.message {
  display: flex;
  justify-content: space-between;
}

// 广告轮播

.el-carousel__item {
  img {
    width: 100%;
    display: block;
    margin: 0 auto;
    border-radius: 5px;
    z-index: 1;
  }
}

.grid-content {
  div {
    p {
      padding: 15px 10px;
      margin: 10px 0;
      background: white;
      border-radius: 5px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

#door {
  width: 80px;
  height: 80px;
  background: #00b1a9;
  border: 1px solid #909399;
  position: fixed;
  right: 5vw;
  bottom: 15vh;
  display: none;
  padding: 5px;
  text-align: center;
  font-size: 20px;
  color: white;
  // color: #545c64;
  border-radius: 50%;
  z-index: 9999999999999;
}

#home {
  width: 600px;
  height: 500px;
  background: #ebe7e7;
  position: fixed;
  right: 5vw;
  bottom: 15vh;
  display: none;
  border-radius: 15px 15px 0 0;
  box-shadow: 1px 2px 20px 4px rgb(0, 0, 0, 20%);
  z-index: 999999999999;
}

.active {
  display: block !important;
}

.right {
  position: relative;
  flex: 1;
  // height: 400px;
  margin: 0 auto;

  .chat-header {
    color: white;
    // color: #545c64;
    text-align: center;
    position: relative;
    font-size: 25px;
    border-radius: 15px 15px 0 0;
    background: #00b1a9;
    line-height: 50px;

    i {
      padding: 5px;
      cursor: pointer;
      position: absolute;
      top: 5px;
      right: 5px;
    }
  }

  .im-footer {
    // position: absolute;
    // bottom: 0;
    // left: 0;
    display: flex;
    width: 100%;

    .im-footer_inp {
      width: 100%;
    }
  }

  .im-record::-webkit-scrollbar {
    width: 10px;
    height: 5px;
    border-radius: 15px;
    -webkit-border-radius: 15px;
  }

  .im-record::-webkit-scrollbar-track-piece {
    background-color: rgb(199, 198, 198);
    border-radius: 15px;
    -webkit-border-radius: 15px;
  }

  .im-record::-webkit-scrollbar-thumb:vertical {
    height: 5px;
    background-color: rgb(160, 158, 158);
    border-radius: 15px;
    -webkit-border-radius: 15px;
  }

  .im-record::-webkit-scrollbar-thumb:horizontal {
    width: 7px;
    background-color: rgb(160, 158, 158);
    border-radius: 15px;
    -webkit-border-radius: 15px;
  }

  .im-record {
    // background: blue;
    width: 100%;
    height: 450px;
    overflow-y: auto;
    overflow-x: hidden;
    box-sizing: border-box;

    // padding: 0 0 35px 0;
    .join-tips {
      position: relative !important;
      display: block;
      width: 100%;
      left: 0 !important;
      transform: none !important;
      color: #cccccc;
      font-size: 15px;
      text-align: center;
    }

    .li {
      position: relative;
      margin-bottom: 15px;
      text-align: left;
      color: #46b0ff;

      p {
        font-size: 16px !important;
        margin: 5px 20px;
      }

      &:after {
        content: "";
        display: block;
        clear: both;
      }

      .message-date {
        font-size: 16px;
        color: #a09f9f;
      }

      &.user {
        text-align: right !important;
      }

      .message-box {
        line-height: 30px;
        font-size: 20px;
        color: #545c64;
      }
    }
  }
}
</style>
